﻿/*
*  Copyright 2012 HEINER DIRECT GmbH & Co. KG
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
* 
* @Author Rafael Dabrowski
* 
*/
var TableConfig = {
    Webs: ko.observableArray([]),
    Web: ko.observable(),
    Lists: ko.observableArray([]),
    List: ko.observable(),
    ViewOptions: ["CAML", "View"],
    ViewOption: ko.observable(""),
    Views: ko.observableArray(),
    View: ko.observable(),
    Fields: ko.observableArray([]),
    Caml: ko.observable(""),
    QueryParam: ko.observable(""),
    GroupFields: ko.observableArray([]),
    curGroupField: ko.observable(),
    deselectedGroupField: ko.observable(),
    DisplayNames: ko.observableArray([]),
    CalcFields: ko.observableArray([]),
    curCalcField: ko.observable(),
    Closed: ko.observable(true)
};

function DisplayName(name, display) {
    this.name = ko.observable(name);
    this.display = ko.observable(display);
    this.remove = function () {
        TableConfig.DisplayNames.remove(this);
    };
}


function newDisplayName(obj) {
    return new DisplayNames(obj.name, obj.display);
}

function CalcField(field, operation, format) {
    this.field = ko.observable(field);
    this.operation = ko.observable(operation);
    this.Display = ko.computed(function () {
        var text = "";
        switch (operation) {
            case "sum":
                text = "Die Werte des Feldes '" + this.field() + "' werden addiert.";
                break;
            case "count":
                text = "Es wird gezählt wie oft das Feld '" + this.field() + "' einen Wert besitzt.";
                break;
            case "avg":
                text = "Es wird der durchschnitt des Feldes '" + this.field() + "'  bestimmt.";
                break;
        }
        return text;
    }, this);
    this.format = ko.observable(format);
    this.remove = function () {
        TableConfig.CalcFields.remove(this);
    };
}

function newCalcField(obj) {
    return new CalcField(obj.field, obj.operation, obj.format);
}

function getWebs() {
    TableConfig.Webs.removeAll(); 
    $().SPServices({
        operation: "GetAllSubWebCollection",
        async: false,
        completefunc: function (xData, Status) {
            $(xData.responseXML).find("Webs > Web").each(function () {
                var $node = $(this);
                TableConfig.Webs.push({
                    name: $node.attr("Title"),
                    url: $node.attr("Url")
                });
            });
        }
    });
}


function getList(url) {
    TableConfig.Lists.removeAll();
    $().SPServices({
        operation: "GetListCollection",
        webURL: url,
        async: false,
        completefunc: function (xData, Status) {
            $(xData.responseXML).find("Lists > List[ShowUser='True']").each(function () {
                var $node = $(this);
                TableConfig.Lists.push({
                    name: $node.attr("Title"),
                    id: $node.attr("ID")
                });
            });
        }
    });
}

function getViews(url, list) {
    TableConfig.Views.removeAll();
    $().SPServices({
        operation: "GetViewCollection",
        webURL: url,
        listName: list,
        async: false,
        completefunc: function (xData, Status) {
            $(xData.responseXML).find("Views > View").each(function () {
                var $node = $(this);
                TableConfig.Views.push({
                    name: $node.attr("DisplayName"),
                    id: $node.attr("Name").replace("{", "").replace("}", ""),
                    url: $node.attr("Url")
                });
            });
        }
    });
}

function getFields(url, list) {
    TableConfig.Fields.removeAll();
    if (TableConfig.ViewOption() == "View") {
        $().SPServices({
            operation: "GetListAndView",
            webURL: url,
            listName: list,
            viewName: TableConfig.View().id,
            async: false,
            completefunc: function (xData, Status) {
                $(xData.responseXML).find("ViewFields > FieldRef").each(function () {
                    var $node = $(this);
                    var $field = $(xData.responseXML).find("Fields > Field[Name='" + $node.attr("Name") + "']");
                    TableConfig.Fields.push({
                        name: $field.attr("DisplayName"),
                        internalName: $field.attr("StaticName"),
                        type: $field.attr("Type")
                    });
                });
            }
        });
    } else {
        $().SPServices({
            operation: "GetList",
            webURL: url,
            listName: list,
            async: false,
            completefunc: function (xData, Status) {
                $(xData.responseXML).find("Fields > Field:not([Hidden])").each(function () {
                    var $node = $(this);
                    TableConfig.Fields.push({
                        name: $node.attr("DisplayName"),
                        internalName: $node.attr("StaticName"),
                        type: $node.attr("Type")
                    });
                });
            }
        });
    }
}

TableConfig.addDisplayName = function () {
    if ($("#newName").val() == "") {
        alert("Bitte den neuen Namen eintragen");
    } else {
        this.DisplayNames.push(new DisplayName($("#oldName").val(), $("#newName").val()));
    }
};

TableConfig.addCalcField = function () {
    this.CalcFields.push(new CalcField(this.curCalcField().name, $("#calcOperation").val(), $("#calcFormat").val()));
};

TableConfig.save = function () {
    $(".JSON").val(ko.toJSON(this));
    $.colorbox.close();
};

TableConfig.Web.subscribe(function (item) {
    getList(item.url);

}, TableConfig);

TableConfig.List.subscribe(function (item) {
    getViews(this.Web().url, item.name);
    getFields(this.Web().url, item.name);
    this.CalcFields.removeAll();
    this.DisplayNames.removeAll();
}, TableConfig);

TableConfig.ViewOption.subscribe(function (item) {
    if (this.Web() && this.List()) {
        getFields(this.Web().url, this.List().name);
    }
    this.GroupFields.removeAll();
}, TableConfig);

TableConfig.CalcOperations = ko.computed(function () {
    var arr = [];
    var add = {
        display: "Addieren",
        value: "sum"
    };
    var cnt = {
        display: "Zählen",
        value: "count"
    };
    var avg = {
        display: "Durchschnitt",
        value: "avg"
    };

    arr.push(cnt);
    if (this.curCalcField()) {

        switch (this.curCalcField().type) {
            case "Number":
            case "Currency":
            case "Integer":
                arr.push(add);
                arr.push(avg);
                break;
            default:
                break;
        }
    }
    return arr;
}, TableConfig);

TableConfig.View.subscribe(function (item) {
    if (this.ViewOption() == "View") {
        getFields(this.Web().url, this.List().name);
        this.GroupFields.removeAll();
    }
}, TableConfig);

TableConfig.curGroupField.subscribe(function (item) {

    if (item) {
        this.GroupFields.push(item);
        this.Fields.remove(item);
    }
}, TableConfig);

TableConfig.deselectedGroupField.subscribe(function (item) {

    if (item) {
        this.Fields.push(item);
        this.GroupFields.remove(item);
    }
}, TableConfig);